package com.ruoyi.bizsys.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.bizsys.service.ISmsAreaNumberConfigService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.mapper.CrsUserMapper;
import com.ruoyi.bizsys.service.ICrsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


/**
 * CRSService业务层处理
 *
 * @author ygenwen
 * @date 2022-08-11
 */
@Service
@Slf4j
public class CrsUserServiceImpl extends ServiceImpl<CrsUserMapper,CrsUser> implements ICrsUserService {

    @Autowired
    private CrsUserMapper crsUserMapper;

    @Autowired
    private CrsUserLogServiceImpl crsUserLogService;


    @Autowired
    private ISmsAreaNumberConfigService smsAreaNumberConfigService;

    @Autowired
    private IAppUserService appUserService;

    private static List<CrsUserLog> crs = new ArrayList<>();
    /**
     * 查询CRS
     *
     * @param id CRSID
     * @return CRS
     */
    @Override
    public CrsUser selectCrsUserById(Integer id) {
        return this.getById(id);
    }

    /**
     * 查询CRS列表
     *
     * @param crsUser CRS
     * @return CRS
     */
    @Override
    public List<CrsUser> selectCrsUserList(CrsUser crsUser) {
        return this.list(new QueryWrapper<>(crsUser).last("order by id desc"));
    }

    /**
     * 新增CRS
     *
     * @param crsUser CRS
     * @return 结果
     */
            @Override
    public int insertCrsUser(CrsUser crsUser) {
                                                                                                                                        crsUser.setCreateTime(DateUtils.getNowDate());
                                                return baseMapper.insert(crsUser);
    }

    /**
     * 修改CRS
     *
     * @param crsUser CRS
     * @return 结果
     */
            @Override
    public int updateCrsUser(CrsUser crsUser) {
                                                                                                                                                            crsUser.setUpdateTime(DateUtils.getNowDate());
                            return baseMapper.updateById(crsUser);
    }

    /**
     * 批量删除CRS
     *
     * @param ids 需要删除的CRSID
     * @return 结果
     */
            @Override
    public int deleteCrsUserByIds(Integer[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除CRS信息
     *
     * @param id CRSID
     * @return 结果
     */
    @Override
    public int deleteCrsUserById(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public List<CrsUser> selectCrsUserByPhone(String phone) {
        return crsUserMapper.selectCrsUserByPhone(phone);
    }

    @Override
    public AjaxResult insertCrsUserList(List<CrsUser> crsUserList) {
        List<CrsUser> users = new ArrayList<>();
        if (CollectionUtils.isEmpty(crsUserList)) {
            return AjaxResult.error("数据为空");
        }
        //防止1000查一次
        List<AppUser>  appUsers = appUserService.selectAppUserList(new AppUser());
        List<CrsUser> crsUsersList = crsUserMapper.selectList(new QueryWrapper<>());
        //去除自身重复数据
        List<CrsUser> newList = getUsers(crsUserList);
        for (int i = 0; i < newList.size(); i++) {
            users.add(newList.get(i));
            if ((i + 1) % 1000 == 0||i == newList.size() - 1) {
                List<CrsUser> crsUsers = checkCallPhone(users,appUsers,crsUsersList);
                if(crsUsers.size() <= 0){
                    log.info("数据为空");
                    return AjaxResult.error("数据为空");
                }
                crsUserMapper.insertCrsUserList(crsUsers);
                users = new ArrayList<CrsUser>();
            }
        }
        //查询上一次新增数据批次号
        CrsUserLog crsUserLog = crsUserLogService.getOne(new QueryWrapper<CrsUserLog>().last("order by id desc limit 1"));
        if(crsUserLog == null){
            //保存剔除日志
            crsUserLogService.saveBatch(crs);
        }else if(crsUserLog !=null && crs.size() > 0 && !crsUserLog.getStageResult().equals(crs.get(0).getStageResult())){
            //保存剔除日志
            crsUserLogService.saveBatch(crs);
        }
        crs = new ArrayList<>();
        return AjaxResult.success("批量导入成功");
    }

    private List<CrsUser> checkCallPhone(List<CrsUser> users,List<AppUser> appUsers,List<CrsUser> crsUsers) {
        //1.在运营商号段内,号码不足11位
        List<CrsUser> loanIouList = getCrsUsers(users);
        //2.查询appUser call_phone 是否存在，存在则剔除
        List<CrsUser> crsList = getCrsUsersByAppUser(appUsers,  loanIouList);
        //3.去除已存在crs的名单
        List<CrsUser> crsUsersList = getCrsUsers(crsUsers, crsList);
        return crsUsersList;
    }

    private List<CrsUser> getUsers(List<CrsUser> crsUsersList) {
        Map<String,List<CrsUser>> crsUserMap = crsUsersList.stream().collect(Collectors.groupingBy(CrsUser::getCallPhone));
        List<CrsUser> userList = crsUserMap.entrySet().stream().filter((obj)-> obj.getValue().size()>1).map(obj->obj.getValue().get(0)).collect(Collectors.toList());
        userList.forEach(e->{
            CrsUserLog crsUserLog = new CrsUserLog();
            crsUserLog.setCallPhone(e.getCallPhone());
            crsUserLog.setChannel(e.getChannel());
            crsUserLog.setStageResult(e.getStageResult());
            crsUserLog.setRemark("号码重复");
            crsUserLog.setUserName(e.getUserName());
            crs.add(crsUserLog);
        });

        Set<CrsUser> playerSet = new TreeSet<>(Comparator.comparing(CrsUser::getCallPhone));
        playerSet.addAll(crsUsersList);
        List<CrsUser> newList = new ArrayList<>(playerSet);
        return newList;
    }

    private List<CrsUser> getCrsUsers(List<CrsUser> crsUsers, List<CrsUser> crsList) {
        HashMap<String,String > crsUserHashMap = new HashMap<>();
        crsUsers.forEach(e->{
            crsUserHashMap.put(e.getCallPhone(),e.getCallPhone());
        });
        List<CrsUser> crsUsersList = new ArrayList<>(crsList);
        crsList.forEach(crsUser -> {
            CrsUserLog crsUserLog = new CrsUserLog();
            if(crsUserHashMap.containsKey(crsUser.getCallPhone())){
                crsUserLog.setCallPhone(crsUser.getCallPhone());
                crsUserLog.setChannel(crsUser.getChannel());
                crsUserLog.setStageResult(crsUser.getStageResult());
                crsUserLog.setRemark("crsUser已存在");
                crsUserLog.setUserName(crsUser.getUserName());
                crs.add(crsUserLog);
                crsUsersList.remove(crsUser);
            }
        });
        return crsUsersList;
    }

    private List<CrsUser> getCrsUsersByAppUser(List<AppUser> appUsers, List<CrsUser> loanIouList) {
        Map<String,String> appUserMap = new HashMap<>();
        appUsers.forEach(e->{
            appUserMap.put(e.getPhone(),e.getPhone());
        });
        List<CrsUser> crsList = new ArrayList<>(loanIouList);
        loanIouList.forEach(user ->{
            CrsUserLog crsUserLog = new CrsUserLog();
            if(appUserMap.containsKey(user.getCallPhone())){
                crsUserLog.setCallPhone(user.getCallPhone());
                crsUserLog.setChannel(user.getChannel());
                crsUserLog.setStageResult(user.getStageResult());
                crsUserLog.setRemark("appUser已存在");
                crsUserLog.setUserName(user.getUserName());
                crs.add(crsUserLog);
                crsList.remove(user);
            }
        });
        return crsList;
    }

    private List<CrsUser> getCrsUsers(List<CrsUser> users) {
        List<SmsAreaNumberConfig> list = smsAreaNumberConfigService.selectSmsAreaNumberConfig();
        Map<String,String> map = new HashMap<>();
        list.forEach(e->{
            map.put(e.getAreaNumber(),e.getAreaNumber());
        });
        List<CrsUser> loanIouList = new ArrayList<>(users);
        users.forEach(user ->{
            CrsUserLog crsUserLog = new CrsUserLog();
            crsUserLog.setCallPhone(user.getCallPhone());
            crsUserLog.setChannel(user.getChannel());
            crsUserLog.setStageResult(user.getStageResult());
            crsUserLog.setRemark("不符合运营商");
            crsUserLog.setUserName(user.getUserName());
            if(!map.containsKey(user.getCallPhone().substring(0,4))){
                crs.add(crsUserLog);
                loanIouList.remove(user);
            } else if (user.getCallPhone().length() < 10) {
                crs.add(crsUserLog);
                loanIouList.remove(user);
            }
        });
        return loanIouList;
    }

}
